# include "vd.h"

#pragma code_seg("PAGE")

VOID VD_Unload (
    IN PDRIVER_OBJECT DriverObject)
{
    PDEVICE_OBJECT				device_object;
	PDEVICE_EXTENSION			device_extension;
	PDEVICE_OBJECT				next_device;
	UNICODE_STRING				Master_sym_link;
	
	DbgPrint("Driver Unload \n");
    
	device_object = DriverObject->DeviceObject;
	device_extension = (PDEVICE_EXTENSION) device_object->DeviceExtension;
	
	DbgPrint("Unload RefCount %d\n",device_object->ReferenceCount);

	ZwClose(dir_handle);
	ExFreePoolWithTag(RegPathW.Buffer,POOL_TAG);
	
	RtlInitUnicodeString(&Master_sym_link, MULTI_VDD_SYMLINK_NAME); 
	IoDeleteSymbolicLink(&Master_sym_link);

	while (device_object)
   {	

	device_extension = (PDEVICE_EXTENSION) device_object->DeviceExtension;
    DbgPrint("Delete device number %d!!! \n",device_extension->DeviceNumber);	

	if (device_extension->terminate_thread == FALSE && device_extension->DeviceNumber != 0)
	{
		device_extension->terminate_thread = TRUE;

		KeSetEvent(
				 &device_extension->request_event,
				 (KPRIORITY) 0,
				 FALSE
				  );

		KeWaitForSingleObject(
							device_extension->thread_pointer,
							Executive,
							KernelMode,
							FALSE,
							NULL
							);
	
		ObDereferenceObject(device_extension->thread_pointer);
	}
	
	next_device = device_object->NextDevice;
	DbgPrint("Delete Device \n");
	IoDeleteDevice(device_object);     
	device_object = next_device;
    
	} 
}